//
//  LGMedicineRecordChartView.m
//  XieHeHeartDisease
//
//  Created by 1234 on 2024/3/7.
//

#import "LGPatientDetailMedicCell.h"
#import "LGMedicineRecordNameCell.h"
#import "LGMedicineHistogramLayer.h"
#import "LGScrollView.h"

#define topMargin     viewPix(65)

#define leftMargin    (viewPix(35)+iPadMargin(10))

//#define lineHeight    viewPix(35)

#define scrollWidth   (Screen_W - viewPix(32))

#define scrollHeight   viewPix(260)

@interface LGPatientDetailMedicCell()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)UICollectionView *collectionView;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)UIButton *completeBtn;
/**   */
@property (nonatomic , strong)UIButton *leaveButton;
/**   */
@property (nonatomic , strong)LGEmptyView *emptyView;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , assign)CGFloat lineHeight;
/**   */
@property (nonatomic , strong)NSArray *dataArray1;
/**   */
@property (nonatomic , strong)NSArray *dataArray2;
/**   */
@property (nonatomic , strong)NSArray *yAxis;
/**   */
@property (nonatomic , strong)NSArray *xAxis;
/**   */
@property (nonatomic , strong)NSMutableArray *layerArray;
/**   */
@property (nonatomic , strong)NSMutableArray *buttonArray;
/**   */
@property (nonatomic , strong)NSMutableArray *yAxisArray;

@end

@implementation LGPatientDetailMedicCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.currentIndex = 0;
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return  self;
}

-(void)setMedicineArray:(NSArray *)medicineArray{
    _medicineArray = medicineArray;
    [self.collectionView reloadData];
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    for (UIView *subView in self.scrollView.subviews) {
        [subView removeFromSuperview];
    }
    if([dataDic isKindOfClass:[NSDictionary class]] && dataDic.allKeys.count>0){
        [self.emptyView stopBufferAction];
        self.dataArray1 = dataDic[@"xAxis1"];
        self.dataArray2 = dataDic[@"xAxis2"];
        CGFloat maxValue = 0;
        for (NSInteger i=0; i<self.dataArray1.count; i++) {
            CGFloat value1 = [self.dataArray1[i] floatValue];
            CGFloat value2 = (i<self.dataArray2.count)?[self.dataArray2[i] floatValue]:0;
            CGFloat total = value1+value2;
            maxValue = (total>maxValue)?total:maxValue;
        }
        CGFloat margin = maxValue/4.0;
        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:@[@"0"]];
        CGFloat number = 0;
        for (NSInteger i=0; i<4; i++) {
            number += margin;
            [tempArray addObject:[NSString stringWithFormat:@"%.2f",number]];
        }
        self.yAxis = tempArray;
        self.xAxis = dataDic[@"yAxis"];
    }else{
        [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:0];
    }
}

-(void)setYAxis:(NSArray *)yAxis{
    _yAxis = yAxis;
    for (UILabel *label in self.yAxisArray) {
        [label removeFromSuperview];
    }
    [self.yAxisArray removeAllObjects];
    
    self.lineHeight = floor((scrollHeight-viewPix(50))/yAxis.count);
    for (NSInteger i=0; i<yAxis.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:LGNSString(yAxis[yAxis.count-1-i]) colorString:@"#5C5C5C" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+self.lineHeight*i, leftMargin, self.lineHeight);
        [self.baseView addSubview:label];
        [self.yAxisArray addObject:label];
    }
}

//创建X轴坐标
-(void)setXAxis:(NSArray *)xAxis{
    _xAxis = xAxis;
    self.totalCount = xAxis.count>0?xAxis.count:1;
    NSInteger count = (self.totalCount>7)?7:self.totalCount;
    self.itemWidth = scrollWidth/count;
    CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
    self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
    [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
    //虚线
    CGFloat lineWidth = (self.itemWidth*xAxis.count+viewPix(50))>scrollWidth?(self.itemWidth*xAxis.count+viewPix(50)):scrollWidth;
    for (NSInteger i=0; i<self.yAxis.count; i++) {
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, self.lineHeight*i, scrollWidth, self.lineHeight)];
        [self.scrollView addSubview:lineView];
    }
    
    //日期、柱状图
    for (LGMedicineHistogramLayer *layer in self.layerArray) {
        [layer removeFromSuperlayer];
    }
    self.layerArray = [NSMutableArray array];
    NSMutableArray *pointArray = [NSMutableArray array];
    CGFloat minValue = [self.yAxis[0] floatValue];
    CGFloat marginV = [self.yAxis[1] floatValue] - [self.yAxis[0] floatValue];
    for (NSInteger i=0; i<xAxis.count; i++) {
        UILabel *dayLabel = [UILabel lableWithText:LGNSString(xAxis[i]) colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(self.itemWidth*i-viewPix(10), scrollHeight-viewPix(50), self.itemWidth, viewPix(20));
        dayLabel.transform = CGAffineTransformRotate(dayLabel.transform, -M_PI_4);
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
        if([LGNSString(xAxis[i]) isEqualToString:@"今日"]){
            CGFloat offset = self.itemWidth*i-(Screen_W-viewPix(32)-leftMargin)/2.0;
            offset = (offset>0)?offset:0;
            [self.scrollView setContentOffset:CGPointMake(offset, 0)];
        }
        CGFloat totalValue = [self.dataArray1[i] floatValue]+[self.dataArray2[i] floatValue];
        CGFloat buttonH = floor((totalValue-minValue)/marginV*self.lineHeight);
        [self createHistogramLayer:i height:buttonH];
    }
}

-(void)createHistogramLayer:(NSInteger)index height:(CGFloat)height{
    if(height > 0){
        CGFloat marginY = scrollHeight-self.lineHeight-height-viewPix(34);
        LGMedicineHistogramLayer *layer = [[LGMedicineHistogramLayer alloc]init];
        layer.frame = CGRectMake(self.itemWidth/2.0+self.itemWidth*index-viewPix(10), marginY, viewPix(20), height);
        layer.percent = [self.dataArray2[index] floatValue]/([self.dataArray1[index] floatValue]+[self.dataArray2[index] floatValue]);
        [self.scrollView.layer addSublayer:layer];
        [self.layerArray addObject:layer];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.medicineArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LGMedicineRecordNameCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.content = LGNSString(self.medicineArray[indexPath.item][@"chemicalName"]);
    cell.isCurrent = (indexPath.item == self.currentIndex)?YES:NO;
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.item != self.currentIndex){
        self.currentIndex = indexPath.item;
        [self.collectionView reloadData];
        if(self.delegate && [self.delegate respondsToSelector:@selector(requestData:content:)]){
            [self.delegate requestData:@"medicine" content:LGNSString(self.medicineArray[indexPath.item][@"id"])];
        }
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(requestMedicineChat:index:)]) {
            [self.delegate requestMedicineChat:LGNSString(self.medicineArray[indexPath.item][@"id"]) index:self.currentIndex];
        }
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *name = LGNSString(self.medicineArray[indexPath.item][@"chemicalName"]);
    CGFloat textW = [name textWidthWithFont:LGFont(14) maxHeight:MAXFLOAT];
    return CGSizeMake(textW+viewPix(24), viewPix(45));
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.clipsToBounds = YES;
    self.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.baseView];
    [self.baseView addSubview:self.collectionView];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.emptyView];
    [self.baseView addSubview:self.completeBtn];
    [self.baseView addSubview:self.leaveButton];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(-15);
        make.left.equalTo(self.contentView).offset(viewPix(16));
        make.right.equalTo(self.contentView).offset(-viewPix(16));
        make.bottom.equalTo(self.contentView).offset(-viewPix(8));
        make.height.equalTo(@(viewPix(355)));
    }];
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(16), -15, Screen_W-viewPix(32), viewPix(355))];
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = 15;
    }
    return _baseView;
}

-(UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = viewPix(10);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, viewPix(10), Screen_W-viewPix(32), viewPix(45)) collectionViewLayout:layout];
        [_collectionView registerClass:[LGMedicineRecordNameCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.contentInset = UIEdgeInsetsMake(0, viewPix(14), 0, viewPix(14));
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"计量" colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _unitLabel.frame = CGRectMake(0, viewPix(56), leftMargin+viewPix(10), viewPix(20));
    }
    return _unitLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth-leftMargin, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(UIButton *)completeBtn{
    if(!_completeBtn){
        _completeBtn = [UIButton buttonWithTitle:@" 已服用" titleFont:LGFont(14) textColor:@"#333333" imageName:@"服药统计-已服用"];
        _completeBtn.frame = CGRectMake((Screen_W-viewPix(32))/2.0-viewPix(100), kMaxY(self.scrollView.frame)-viewPix(5), viewPix(70), viewPix(30));
    }
    return _completeBtn;
}

-(UIButton *)leaveButton{
    if(!_leaveButton){
        _leaveButton = [UIButton buttonWithTitle:@" 漏服" titleFont:LGFont(14) textColor:@"#333333" imageName:@"服药统计-漏服"];
        _leaveButton.frame = CGRectMake((Screen_W-viewPix(32))/2.0+viewPix(30), kMinY(self.completeBtn.frame), viewPix(70), viewPix(30));
    }
    return _leaveButton;
}

-(LGEmptyView *)emptyView{
    if(!_emptyView){
        _emptyView = [[LGEmptyView alloc]initWithFrame:CGRectMake(0, topMargin, scrollWidth, scrollHeight)];
        _emptyView.backgroundColor = [UIColor whiteColor];
        _emptyView.userInteractionEnabled = NO;
        _emptyView.hidden = YES;
    }
    return _emptyView;
}

-(NSMutableArray *)yAxisArray{
    if(!_yAxisArray){
        _yAxisArray = [NSMutableArray array];
    }
    return _yAxisArray;
}

@end
